package com.baseframe.oss.builds;

import com.alibaba.fastjson.JSON;
import com.baseframe.oss.constant.BaseOssConstant;
import com.baseframe.oss.entity.Oss;
import com.baseframe.oss.execption.OssException;
import com.baseframe.oss.template.AliOssTemplate;
import com.baseframe.oss.template.OssTemplate;
//import com.baseframe.oss.template.TencentCosTemplate;
import com.baseframe.oss.template.TencentCosTemplate;
import com.baseframe.oss.template.UnknownOssTemple;
import com.baseframe.tool.func.Func;
import com.baseframe.tool.result.R;
import com.baseframe.tool.utils.redis.CommonRedisUtil;

public class BaseOssBuilds {

    public static <E> OssTemplate build(Oss oss, Func<String,Oss> func){

        //从redis中获取

        String ossJson = CommonRedisUtil.getValue(BaseOssConstant.REDIS_KEY + oss.getId());

        if (ossJson!=null){
            oss = JSON.parseObject(ossJson, Oss.class);
            return getTemplate(oss);

        }
        //从数据库中获取
        R<Oss> ossR = func.find(oss.getId());
        oss = ossR.getData();
        if (oss == null){
            throw new OssException("获取对象存储配置失败~");
        }
        //存储到redis中去
        CommonRedisUtil.setValue(BaseOssConstant.REDIS_KEY+oss.getId(),JSON.toJSONString(oss));



        return getTemplate(oss);
    }

    public static OssTemplate getTemplate(Oss oss){
        OssTemplate ossTemplate = null;
        switch (oss.getType()){
            case ALI:
                ossTemplate = new AliOssTemplate(oss);
                break;
            case TENCENT:
                ossTemplate = new TencentCosTemplate(oss);
                break;
            default:
                ossTemplate = new UnknownOssTemple(oss);
        }

        return ossTemplate;

    }
}
